package com.sylar.happyreader.tools;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.WeakHashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.sylar.happyreader.BookApplication;

public final class ImageCache extends WeakHashMap<String, Bitmap> {

	/**
	 * 是否缓存
	 * 
	 * @param url
	 * @return 是否已被缓存
	 */
	public boolean isCached(String url) {
		/**
		 * 在内存中是否存在
		 */
		boolean isExistsMemory = containsKey(url) && (get(url) != null);

		return isExistsMemory == false ? isExistedLocal(url) : isExistsMemory;

	}

	/**
	 * 重写get方法 (是从内存中去get)
	 */
	@Override
	public Bitmap get(Object key) {
		return super.get(key);
	}

	/**
	 * 重写put方法,在图片put到内存的同时将其缓存到本地 在缓存到本地的同时将其key(即图片的url地址)中的 "/"转换为"__"
	 * 然后作为文件件进行缓存
	 */
	@Override
	public Bitmap put(String key, Bitmap value) {
		String fileName = key.replaceAll(Config.CoverUri, "__"); // 2个下划线
		fileName = fileName.replaceAll("/", "_"); // 1个下划线
		File dir = BookApplication.getInstance().getCacheDir();
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// sd card 可用
			dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+Config.APPTAG);
			if(!dir.exists())
			dir.mkdir();
		} else {
			dir = BookApplication.getInstance().getCacheDir();
			// 当前不可用
		}

		File file = new File(dir, fileName);
		
		OutputStream outputStream = null;
		try {
			if(!file.exists())
				file.createNewFile();
			outputStream = new FileOutputStream(file);
			boolean isok = value.compress(Bitmap.CompressFormat.PNG, 100,
					outputStream);
			outputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
					outputStream = null;
				} catch (IOException e) {
				}

			}
		}
		return super.put(key, value);
	}

	/**
	 * 缓存图片
	 * 
	 * @param key
	 * @param value
	 * @param isPutInLocal
	 *            是否要将图片缓存到笨地
	 * @return 缓存图片
	 */
	public Bitmap put(String key, Bitmap value, boolean isPutInLocal) {
		if (!isPutInLocal) {
			return super.put(key, value);
		} else {
			return put(key, value);
		}
	}

	public byte[] toLocalBitmap(String url) {
		String fileName = url.replaceAll(Config.CoverUri, "__"); // 2个下划线
		fileName = fileName.replaceAll("/", "_"); // 1个下划线
		File dir = BookApplication.getInstance().getCacheDir();
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// sd card 可用
			dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+Config.APPTAG);
		} else {
			dir = BookApplication.getInstance().getCacheDir();
			// 当前不可用
		}
		File file = new File(dir, fileName);
		if (!file.exists()) {
			return null;
		}
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(file);
			byte[] data = readInputStream(inputStream);
			return data;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
					inputStream = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	/**
	 * 判断是否缓存到了本地
	 * 
	 * @param url
	 * @return 该图片在本地cache理面是否存在
	 */
	private boolean isExistedLocal(String url) {
		/**
		 * key(即图片的url地址)中的 "/"转换为"__"然后到缓存中查询
		 */
		String fileName = url.replaceAll(Config.CoverUri, "__"); // 2个下划线
		fileName = fileName.replaceAll("/", "_"); // 1个下划线
		File dir = BookApplication.getInstance().getCacheDir();
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// sd card 可用
			dir = new File(Environment.getExternalStorageDirectory().getPath()+"/"+Config.APPTAG);
		} else {
			dir = BookApplication.getInstance().getCacheDir();
			// 当前不可用
		}
		File file = new File(dir,
				fileName);
		if (!file.exists()) {
			return false;
		}
		boolean isExist = false;
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(file);
			byte[] data = readInputStream(inputStream);
			Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
			if (bitmap != null) {
				// 本地cache中已经存在，只需要将bitmap缓存到内存中即可
				this.put(url, bitmap, false);
				isExist = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
					inputStream = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return isExist;
	}

	public static byte[] readInputStream(InputStream inStream) throws Exception {
		// GZIPInputStream is = new GZIPInputStream(inStream);
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}

}